package com.haiheng.module_main.mode

import android.text.TextUtils
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.haiheng.common.api.API
import com.haiheng.common.bean.AccessTokenBean
import com.haiheng.common.bean.FaceSynResource
import com.haiheng.common.bean.FaceSynResourceBean
import com.haiheng.common.bean.ResourceMeta
import com.haiheng.common.constant.AppConstant
import com.haiheng.library.log.LogUtils
import com.haiheng.library.log.LogWriter
import com.haiheng.library_base.http.*
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.library_base.utils.SPUtils
import kotlinx.coroutines.launch
import java.io.File
import java.util.*
import kotlin.collections.ArrayList

/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2022/5/25 0025
 * @Version: 1.0
 */
class SettingViewModel : BaseViewModel() {
    val lastResourceBundleRecordId  = MutableLiveData<Int>()
    var isSynFaceFinish = MutableLiveData<Boolean>()




    fun synFaceDate(){
        viewModelScope.launch {
            var token = AppConstant.getFaceToken()
            if (token.isBlank()){
                getFaceToken()
            }
            val request = HttpRequest(API.PATH.SYNCHRONIZE_FACE_RES_PATH)
                .putHeader(Domain.KEY_NAME,Domain.VALUE_FACE)
                .putHeader(API.PARAM.PARAM_HEADER_TOKEN,token)
                .setJsonObjec(RequestDataHelper.getFaceReqData())
            var response = postJson<FaceSynResourceBean>(request){}
            if ("0".equals(response.errorCode)){
                if (response.result != null){
                    lastResourceBundleRecordId.postValue(response.result!!.lastResourceBundleRecordId)
                    isSynFaceFinish.postValue(false)
                    if (AppConstant.isOpenLog()){
                        LogWriter.e("获取人脸同步数据更新：${response.result!!.toJson()}")
                    }
                    downloadPicAndImport(response.result!!)
                }else{
                    if (AppConstant.isOpenLog()){
                        LogWriter.e("同步结束 没有相关同步信息")
                    }
                    //说明同步结束
                    isSynFaceFinish.postValue(true)
                }
            }else{
                if(response.errorMsg.contains("Unauthorized")){
                    getFaceToken()
                }
                if (AppConstant.isOpenLog()){
                    LogWriter.e("获取人脸同步数据失败：${response.toJson()}")
                }
            }
        }
    }

    fun getFaceToken(){
        api {
            val request = HttpRequest(API.PATH.GET_FACE_TOKEN_PATH)
                .putHeader(Domain.KEY_NAME,Domain.VALUE_FACE)
                .setJsonObjec(RequestDataHelper.getFaceTokenReqData())
            var response = postJson<AccessTokenBean>(request){}

            if (response != null && response.accessToken != null){
                LogUtils.d("获取人脸token成功，更新本地人脸token:"+response.toJson())
                SPUtils.getInstance().put(AppConstant.SP_FACE_TOKEN,"${response.type} ${response.accessToken}")
            }else{
                if (AppConstant.isOpenLog()){
                    LogWriter.e("获取人脸token失败 ${response.toJson()}")
                }
            }
        }
    }

    fun downloadPicAndImport(result: FaceSynResource) {
      /*  viewModelScope.launch {
            try {
                var importList = ArrayList<ImportFileInfo>()
                var downCount = 0;//下载数量
                for (m in result.resourceMetaList){
                    if (m.optType.equals("Add")){
                        val imgPath= m.faceImagePath
                        val imgName = "${m.name}"
                        // 1、获取导入目录 /sdcard/Face-Import
                        val batchImportDir = FileUtils.getBatchImportDirectory()

                        if (TextUtils.isEmpty(imgPath)){
                            continue
                        }
                        val suffix = imgPath.substring(imgPath.lastIndexOf("."))
                        val filePathName = "${batchImportDir.absolutePath}" +
                                "${File.separator}" +
                                "${imgName}" +
                                "${suffix}"
                        val downUrl = API.getFaceUrl() + imgPath
                        //构建请求体，传入请求参数

                        val request = HttpRequest(downUrl)
                        //以get方式发起网络请求
                        val response = download(request, filePathName){
                            LogUtils.e("图片下载完成进度:"+downCount)
                            // 开始导入
                        }
                        response.errorMsg = filePathName
                        //通过LiveData通知界面更新
                        LogUtils.i("下载图片结果："+response.toJson()  )
                        downCount++
                        if (response.errorCode.equals("0")){
                            if (AppConstant.isOpenLog()){
                                LogWriter.e("${imgName} 图片下载完成数量："+downCount)
                            }
                            val importFileInfo = ImportFileInfo()
                            importFileInfo.filePathName = filePathName
                            importFileInfo.urserInfo = Gson().toJson(m).toString()
                            importList.add(importFileInfo)
                            if (downCount == result.resourceMetaList.size){
                                LogUtils.e("图片全部下载结束"+downCount)
                            }
                        }else{
                            if (AppConstant.isOpenLog()){
                                LogWriter.e("人脸图片下载失败：${m}")
                            }
                        }

                    }else if (m.optType.equals("Delete")){
                        //删除人脸
                        deleteFaceDate(m)
                    }
                }
                LogUtils.i("图片下载成功 开始导入")
                importImage(importList)
            }catch (ex:Exception){
                LogWriter.e("图片下载导入异常 downloadPicAndImport:${ex}")
            }
        }*/
    }

    fun deleteFaceDate(m: ResourceMeta) {
        viewModelScope.launch {
            try {
                if (!TextUtils.isEmpty(m.relativeIdentityID)){
//                    var deletResult =  FaceApi.getInstance().userDelete(m.relativeIdentityID)
//                    LogUtils.d("删除人脸${m.relativeIdentityID}用户 result：${deletResult}")
                }
            }catch (ex:Exception){
                LogWriter.e("删除异常:${ex} ${m}")
            }
        }
    }



}